package com.oocl.euc.core.attachment.service;

import com.oocl.euc.core.attachment.model.Attachment;
import com.oocl.euc.core.attachment.repository.AttachmentRepository;
import com.oocl.euc.framework.base.persistence.IBaseRepository;
import com.oocl.euc.framework.base.service.BaseService;
import com.oocl.euc.framework.common.utils.MD5Utils;
import com.oocl.euc.framework.common.utils.PropertiesLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class AttachmentService extends BaseService<Attachment, Long> {
    private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);

    @Autowired
    AttachmentRepository attachmentRepository;

    @Override
    protected IBaseRepository<Attachment, Long> getRepository() {
        return attachmentRepository;
    }

    public Attachment uploadAttachment(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        String md5Code = MD5Utils.getMD5(file.getInputStream());
        List<Attachment> attachments = attachmentRepository.findByMd5Code(md5Code);
        if (!attachments.isEmpty()) {
            for(Attachment attach: attachments){
                if(file.getOriginalFilename().equals(attach.getFileName())){
                    return attach;
                }
            }
            return addAttachment(file, md5Code);
        } else {
            return addAttachment(file, md5Code);
        }
    }

    private Attachment addAttachment(MultipartFile file, String md5Code) throws IOException {
        Attachment attachment = new Attachment();
        attachment.setContent(file.getBytes());
        attachment.setContentType(file.getContentType());
        attachment.setFileName(file.getOriginalFilename());
        attachment.setLength(file.getSize());
        attachment.setMd5Code(md5Code);
        return attachmentRepository.save(attachment);
    }


    public ResponseEntity downloadAttachment(Long attachmentId) {
        try {
            Attachment attachment = findOne(attachmentId);
            if (attachment == null) {
                return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
            }
            byte[] outputFile = attachment.getContent();
            String fileName = attachment.getFileName();
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.set("charset", "utf-8");
            responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            responseHeaders.setContentLength(attachment.getLength());
            responseHeaders.set("Content-disposition", "attachment;filename="
                    + fileName);
            return new ResponseEntity<byte[]>(outputFile, responseHeaders, HttpStatus.OK);
        } catch (Exception ex) {
            logger.error(ex.toString());
            return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.BAD_REQUEST);
        }
    }
}
